<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { ref } from 'vue'
import { Page, useVbenModal } from '@vben/common-ui'
import { Button, Input, message, Popconfirm, Tag } from 'ant-design-vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { exportExpiredData, getPurchaseBomDetailList, doSignFinish } from '#/api/purchase'
import { getSupplyList, getAdminList } from '#/api/common'
import { useDebounceFn } from '@vueuse/core'

import RevicedLog from './modules/revicedLog.vue'

interface RowType {
  [key: string]: any
}
const params = ref<any>({
  quick_search: '',
})
// 表格相关
const selectedRows = ref<RowType[]>([])

const keyword = ref({
  admin_id: '',
  supply_id: '',
})

// 默认排序
const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'purchase_bom_detail_id',
  order: 'desc',
}

// 导出数据
const getExport = async () => {
  const hide = message.loading('正在导出...', 0)
  try {
    const search = await gridApi.formApi.getFiltersValues()
    await exportExpiredData({ search })
  } catch (e) {
    message.error('导出失败')
  } finally {
    hide()
  }
}

const fetchSupplyOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getSupplyList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'supply.id',
    select: true,
  })

  return list.map((item) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}

const fetchAdminIdOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getAdminList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    select: true,
  })

  return list.map((item) => ({
    label: item.realname,
    value: item.id,
  }))
}

// 表单配置
const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Input',
      fieldName: 'template_no',
      label: '简码',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'purchase*purchase_sn',
      label: '手工单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'purchase*purchase_time',
      label: '采购时间',
      operator: 'RANGE',
      // formItemClass: 'col-span-2',  //占两列
      componentProps: {
        // showTime: true,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'Input',
      fieldName: 'expired_date',
      label: '逾期天数',
      operator: 'RANGE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'expired_status',
      label: '逾期状态',
      operator: 'rangeIn',
      componentProps: {
        mode: 'multiple',
        options: [
          { label: '未逾期', value: 1 },
          { label: '即将逾期', value: 2 },
          { label: '逾期', value: 3 },
        ],
        placeholder: '请选择',
      },
    },
    {
      component: 'Select',
      fieldName: 'reviced_status',
      label: '到料状态',
      operator: 'rangeIn',
      componentProps: {
        mode: 'multiple',
        options: [
          { label: '未到', value: 1 },
          { label: '部分到', value: 2 },
          { label: '到料完成', value: 3 },
        ],
        placeholder: '请选择',
      },
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchSupplyOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.supply_id = value
          }, 300),
          params: {
            keyword: keyword.value.supply_id || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword.value.supply_id = ''
          },
        }
      },
      fieldName: 'supply_id',
      label: '供应商',
      operator: '=',
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchAdminIdOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.supply_id = value
          }, 300),
          params: {
            keyword: keyword.value.supply_id || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword.value.supply_id = ''
          },
        }
      },
      fieldName: 'purchase*create_admin',
      label: '下单人',
      operator: '=',
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'purchase_bom_detail_id',
    // isCurrent: true,
    isHover: true,
  },
  columnConfig: {
    useKey: true,
  },
  cellConfig: {
    height: 70,
  },
  columns: [
    { type: 'checkbox', width: 50, fixed: 'left' },
    { field: 'template_no', width: 80, title: '简码', fixed: 'left' },
    {
      field: 'material_info',
      width: 300,
      title: '物料',
      type: 'html',
    },
    {
      field: 'purchase_info',
      width: 140,
      title: '采购信息',
      type: 'html',
    },
    {
      field: 'confirm_info',
      width: 120,
      title: '数量',
      type: 'html',
    },
    { field: 'purchase.purchase_sn', width: 140, title: '手工单号' },
    { field: 'purchase.purchase_time', width: 140, title: '采购时间' },
    { field: 'expired_date', width: 80, title: '逾期天数' },
    {
      field: 'expired_status',
      width: 80,
      title: '逾期',
      slots: { default: 'expiredStatus' },
    },
    {
      field: 'attr_info',
      width: 120,
      title: '属性',
      type: 'html',
    },
    { field: 'remark', width: 120, title: '备注' },
    {
      field: 'reviced_status',
      width: 100,
      title: '到料状态',
      slots: { default: 'revicedStatus' },
    },
    { field: 'create_user_name', width: 100, title: '下单人' },
    {
      field: 'reviced_time',
      width: 145,
      title: '最后收料时间',
      type: 'html',
    },
    {
      field: 'purchase_time_info',
      width: 145,
      title: '交期/采购',
      type: 'html',
    },
    {
      field: 'operation',
      fixed: 'right',
      slots: { default: 'operation' },
      title: '操作',
      width: 170,
    },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    pageSize: 20,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }, formValues) => {
        const search = await gridApi.formApi.getFiltersValues()
        const res = await getPurchaseBomDetailList({
          limit: page.pageSize,
          tableSize: 'small',
          search,
          quick_search: params.value.quick_search,
        })

        return {
          items: res.list,
          total: res.total,
        }
      },
    },
    sort: true,
  },
  sortConfig: {
    defaultSort,
    remote: true,
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'purchase_bom_detail_list',
  customConfig: {
    storage: true,
  },
}

// 获取逾期状态标签颜色
const getExpiredStatusColor = (value: number) => {
  switch (value) {
    case 1: {
      return 'success' // 未逾期
    }
    case 2: {
      return 'warning' // 即将逾期
    }
    case 3: {
      return 'error' // 逾期
    }
    default: {
      return 'default'
    }
  }
}

// 获取到料状态标签颜色
const getRevicedStatusColor = (value: number) => {
  switch (value) {
    case 1: {
      return 'error' // 未到
    }
    case 2: {
      return 'warning' // 部分到
    }
    case 3: {
      return 'success' // 到料完成
    }
    default: {
      return 'default'
    }
  }
}

// 获取逾期状态文本
const getExpiredStatusText = (value: number) => {
  switch (value) {
    case 1: {
      return '未逾期'
    }
    case 2: {
      return '即将逾期'
    }
    case 3: {
      return '逾期'
    }
    default: {
      return ''
    }
  }
}

// 获取到料状态文本
const getRevicedStatusText = (value: number) => {
  switch (value) {
    case 1: {
      return '未到'
    }
    case 2: {
      return '部分到'
    }
    case 3: {
      return '到料完成'
    }
    default: {
      return ''
    }
  }
}

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    }
  },
})
const debouncedReload = useDebounceFn(gridApi.reload, 1000)

// 事件处理
const handleshowRecordData = (row: RowType) => {
  RevicedLogModalApi.setData({
    info: row,
  }).open()
}

const handleSignFinish = (row: RowType) => {
  doSignFinish({
    purchase_bom_detail_id: row.purchase_bom_detail_id,
  }).then(() => {
    message.success('已标记')
    gridApi.query()
  })
}

const [RevicedLogModal, RevicedLogModalApi] = useVbenModal({
  connectedComponent: RevicedLog,
})

function sync(row: any, RowType: any) {
  throw new Error('Function not implemented.')
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <!-- 自定义逾期天数为两个输入框 -->
      <template #form-expired_date="slotProps">
        <div class="flex items-center">
          <Input style="width: 100px" placeholder="最小天数" :value="slotProps.value?.[0] ?? ''" @update:value="(v) => slotProps['onUpdate:value']([v, slotProps.value?.[1] ?? ''])" />
          <span class="mx-2">~</span>
          <Input style="width: 100px" placeholder="最大天数" :value="slotProps.value?.[1] ?? ''" @update:value="(v) => slotProps['onUpdate:value']([slotProps.value?.[0] ?? '', v])" />
        </div>
      </template>

      <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="getExport">导出</Button>
      </template>
      <template #toolbar-tools>
        <div>
          <Input type="text" placeholder="供应商、物料名称模糊搜索" v-model:value="params.quick_search" :allow-clear="true" @input="debouncedReload" />
        </div>
      </template>

      <template #expiredStatus="{ row }">
        <Tag :color="getExpiredStatusColor(row.expired_status)">
          {{ getExpiredStatusText(row.expired_status) }}
        </Tag>
      </template>

      <template #revicedStatus="{ row }">
        <Tag :color="getRevicedStatusColor(row.reviced_status)">
          {{ getRevicedStatusText(row.reviced_status) }}
        </Tag>
      </template>

      <template #operation="{ row }">
        <Button class="mr-2" type="primary" size="small" @click.stop="handleshowRecordData(row)">收料记录</Button>
        <Popconfirm title="确认标记" description="确认标记吗？" ok-text="确认" cancel-text="取消" @confirm="handleSignFinish(row)">
          <Button type="primary" size="small" danger>标记</Button>
        </Popconfirm>
      </template>
    </Grid>
    <RevicedLogModal />
  </Page>
</template>
